package netbayServlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import util.String.StringUtil;
import util.jQueryForm.jQueryFormFormatterUtil;
import util.jQueryForm.jQueryFormSelector;

import netbay.NetbayUtility;
import netbay.TransactionManager;
import netbay.UserManager;

/**
 * Servlet implementation class EditAdminServlet
 */
public class EditAdminServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EditAdminServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    public void init() {
		String configPath = getServletContext().getRealPath(
				"/WEB-INF/config.properties");
		NetbayUtility.init(configPath);
	}
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");  // ensures that user input is interpreted as // 8-bit Unicode (e.g., for Czech characters)
        response.setContentType("text/json;charset=utf-8");
        HttpSession session = request.getSession();
        String url = "";
        String viewId = ((!StringUtil.isNullOrEmpty((String)(request.getParameter("id")))) ? (String)request.getParameter("id"): "null");
        request.setAttribute("id", viewId);
        String userId = ((!StringUtil.isNullOrEmpty((String)(session.getAttribute("userId")))) ? (String)session.getAttribute("userId"): "null");
        if(!(userId.equals("null"))){
        	url = "/EditAdmin.jsp";
        }
        else{
        	url = "/Login.jsp";
        }
        try{
        	request.getRequestDispatcher(url).forward(request, response);
		} catch (Exception ex) {
            ex.printStackTrace();
        }
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 request.setCharacterEncoding("UTF-8");
		 response.setContentType("text/json;charset=utf-8");
		 String userPath = request.getServletPath();
		 PrintWriter out = response.getWriter();
		 HttpSession session = request.getSession();
	     String strJson = "{}";
	     UserManager um = new UserManager();
	    if (userPath.equals("/EditAdminServlet/SaveUser")) {
	    	try {
		    	 Integer id = Integer.parseInt((!StringUtil.isNullOrEmpty(request.getParameter("id"))) ? request.getParameter("id").trim() : "");
			     String oldpassword = (!StringUtil.isNullOrEmpty(request.getParameter("oldpassword"))) ? request.getParameter("oldpassword").trim() : "";
		    	 String password = (!StringUtil.isNullOrEmpty(request.getParameter("password"))) ? request.getParameter("password").trim() : "";
			     String rdoRecordType = (!StringUtil.isNullOrEmpty(request.getParameter("rdoRecordType"))) ? request.getParameter("rdoRecordType").trim() : "";
			     String firstname = (!StringUtil.isNullOrEmpty(request.getParameter("firstname"))) ? request.getParameter("firstname").trim() : "";
			     String lastname = (!StringUtil.isNullOrEmpty(request.getParameter("lastname"))) ? request.getParameter("lastname").trim() : "";
			     String address = (!StringUtil.isNullOrEmpty(request.getParameter("address"))) ? request.getParameter("address").trim() : "";
			     String tel = (!StringUtil.isNullOrEmpty(request.getParameter("tel"))) ? request.getParameter("tel").trim() : "";
			     String fax = (!StringUtil.isNullOrEmpty(request.getParameter("fax"))) ? request.getParameter("fax").trim() : "";
			     String email = (!StringUtil.isNullOrEmpty(request.getParameter("email"))) ? request.getParameter("email").trim() : "";
			     String hashPassword = UserManager.hashPassword(password);
				 boolean result = false;
			 
				result = um.editUser(id,oldpassword,password,hashPassword,rdoRecordType,firstname,lastname,address,tel,fax,email);
		
				String username = um.getUsernameByid(id);
			
				 if(result){
					 um.saveLog((String)session.getAttribute("userId"),um.actionEditUser,username);
					 strJson = "{\"success\": \"\"}";
				 }else  strJson = "{\"error\": \"Cannot edit user.\"}";
				//out.println(strJson);
	         } catch (Exception ex) {
	        	 strJson = "{\"error\": \"" + ex.getMessage() + "\"}" ; 
	         }
	         out.println(strJson);
	     }else if (userPath.equals("/EditAdminServlet/CheckOldPassword")) {
	    	 try {
		    	 Integer id = Integer.parseInt((!StringUtil.isNullOrEmpty(request.getParameter("id"))) ? request.getParameter("id").trim() : "");
		    	 String oldpassword = (!StringUtil.isNullOrEmpty(request.getParameter("oldpassword"))) ? request.getParameter("oldpassword").trim() : "";
		    	 String hashOldPassword = UserManager.hashPassword(oldpassword);
				 boolean result = false;
				 result = um.checkOldPassword(id,hashOldPassword);

				 if(result){
					 strJson = "{\"success\": \"\"}";
				 }else  strJson = "{\"error\": \"Cannot check password.\"}";
				//out.println(strJson);
	         } catch (Exception ex) {
	        	 strJson = "{\"error\": \"" + ex.getMessage() + "\"}" ; 
	         }
	         out.println(strJson);
	     }else if (userPath.equals("/EditAdminServlet/DisplayData")){
	    	
	    	   String id = (!StringUtil.isNullOrEmpty(request.getParameter("id"))) ? request.getParameter("id").trim() : "";

	    	   List result = um.getDataUserById(Integer.parseInt(id));
	    	   request.setAttribute("id", id);
	                if (!result.isEmpty()){
					    try {
					        out = response.getWriter();
					        request.getAttributeNames();
					        strJson = DisplayData(result);
					        out.println(strJson);
					    } catch (Exception ex) {
					    	strJson = "{\"error\": \"" + ex.getMessage() + "\"}" ;
					    	out.println(strJson);
					        //out = response.getWriter();
					        //out.write(strJson);
					    } finally {
					        out = null;
					        strJson = "";
					    }
					} else {
					out = response.getWriter();
					out.write(strJson);
					}
	     }
	     
	     
	}
	public String DisplayData(List data) throws Exception {
        jQueryFormFormatterUtil objJQueryFormFormatterUtil;
        String strJson = "{}";
        String username = "";
        String password = "";
        String group = "";
        String beforeName = "";
        String firstName = "";
        String lastName = "";
        String address = "";
        String tel = "";
        String fax = "";
        String email = "";
        Map<String, String> mapHtml = null;
        Map<String, String> mapText = null;
        Map<String, String> mapVal = null;
        List<jQueryFormSelector> mapAttrs = null;
        jQueryFormSelector attr = null;
        Map<String, String> mapAttrItem = null;
        Map<String, String> mapRemoveAttr = null;

        try {
        	username = (String) data.get(0);
        	password = (String) data.get(1);
        	group = (String) data.get(2);
            beforeName =(String) data.get(3);
            firstName = (String) data.get(4);
            lastName = (String) data.get(5);
            address = (String) data.get(6);
            tel = (String) data.get(7);
            fax = (String) data.get(8);
            email = (String) data.get(9);
            mapHtml = new LinkedHashMap<String, String>();
            mapVal = new LinkedHashMap<String, String>();
            mapHtml.put("#username", username);
            mapVal.put("#firstname", firstName);
            mapVal.put("#lastname", lastName);
            mapVal.put("#address", address);
            mapVal.put("#tel", tel);
            mapVal.put("#fax", fax);
            mapVal.put("#email", email);
            
            mapAttrs = new ArrayList<jQueryFormSelector>();
            attr = new jQueryFormSelector();
            attr.setId("[name='rdoRecordType'][value='"+beforeName+"']");
            mapAttrItem = new LinkedHashMap<String, String>();
            mapAttrItem.put("checked", "checked");
            attr.setMapAttr(mapAttrItem);
            mapAttrs.add(attr);
            objJQueryFormFormatterUtil = new jQueryFormFormatterUtil();
            strJson = objJQueryFormFormatterUtil.setHtml(mapHtml).setVal(mapVal).setAttr(mapAttrs).buildJson();

            return strJson;
       
        } catch (Exception ex) {
        	throw  new Exception("Display error.");
            //return strJson;
        } finally {
            strJson = "";

        }

    }
}
